// controllers/bookController.js
import Book  from ('../models/Book.js');

// 获取所有图书
exports.getAllBooks = async (req, res) => {
  try {
    const books = await Book.find({});
    res.json(books);
  } catch (error) {
    res.status(500).send(error);
  }
};

// 添加图书
exports.addBook = async (req, res) => {
  const newBook = new Book(req.body);
  try {
    const savedBook = await newBook.save();
    res.status(201).json(savedBook);
  } catch (error) {
    res.status(500).send(error);
  }
};

// 删除图书
exports.deleteBook = async (req, res) => {
  try {
    const deletedBook = await Book.findByIdAndDelete(req.params.id);
    if (!deletedBook) {
      return res.status(404).send('No item found');
    }
    res.status(200).send();
  } catch (error) {
    res.status(500).send(error);
  }
};

// 更新图书
exports.updateBook = async (req, res) => {
  try {
    const updatedBook = await Book.findByIdAndUpdate(req.params.id, req.body, { new: true });
    res.json(updatedBook);
  } catch (error) {
    res.status(500).send(error);
  }
};
